package qianfeng.com.meijiadaka;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.Vitamio;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;
import qianfeng.com.meijiadaka.adapter.shop_details.SpecialDetailsAdapter;
import qianfeng.com.meijiadaka.bean.detail.SpecialBeanAbove;
import qianfeng.com.meijiadaka.bean.detail.SpecialBeanBelow;
import qianfeng.com.meijiadaka.utils.DensityUtils;

public class SpeciaDetailsActivity extends AppCompatActivity {

    //路径：美咖专题
    private String id;
    private String PATH_DETAIL = "http://home.naildaka.com/vapi/v4/home/tutorials/topics/detail?topicId=";
    private String HEADUID = "&uid=null";
    private String PATH_COMMENTS = "http://home.naildaka.com/vapi/v4/home/tutorials/topics/comments?topicId=";
    private String BELOWUID = "&uid=null&pageNo=1";
    VideoView mVideoView;
    @BindView(R.id.speciaDetail_listview)
    ListView mListView;
    //头布局UI
    View headView;
    ProgressBar pb;
    TextView tvTitle, tvTags, tvPlaycounts;
    ImageView image_play, image_fullScreen;
    private SpecialBeanAbove mSpecialBeanAbove;
    private SpecialBeanBelow mSpecialBeanBelow;
    private SpecialDetailsAdapter mAdapter;
    private StringBuffer sb;
    String tagString;
    private List<Object> lists;
    private List<Object> list;


    private View mVolumeBrightnessLayout;
    private ImageView mOperationBg;
    private ImageView mOperationPercent;
    private AudioManager mAudioManager;
    /** 最大声音 */
    private int mMaxVolume;
    /** 当前声音 */
    private int mVolume = -1;
    /** 当前亮度 */
    private float mBrightness = -1f;
    /** 当前缩放模式 */
    private int mLayout = VideoView.VIDEO_LAYOUT_ZOOM;
    private GestureDetector mGestureDetector;
    private MediaController mMediaController;


    private boolean sensor_flag=true;
    private boolean stretch_flag=true;
    private SensorManager sm;
    private OrientationSensorListener listener;
    private Sensor sensor;
    private int screenWidth;
    private int screenHeight;
    private SensorManager sm1;
    private Sensor sensor1;
    private OrientationSensorListener2 listener1;
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 888:
                    int orientation = msg.arg1;
                    if (orientation>45&&orientation<135) {

                    }else if (orientation>135&&orientation<225){

                    }else if (orientation>225&&orientation<315){
                        System.out.println("切换成横屏");
                        SpeciaDetailsActivity.this.setRequestedOrientation(0);
                        sensor_flag = false;
                        stretch_flag=false;

                    }else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){
                        System.out.println("切换成竖屏");
                        SpeciaDetailsActivity.this.setRequestedOrientation(1);
                        sensor_flag = true;
                        stretch_flag=true;

                    }
                    break;
                default:
                    break;
            }

        };
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Vitamio.isInitialized(this);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
        setContentView(R.layout.activity_specia_details);
        ButterKnife.bind(this);
        mSpecialBeanAbove = new SpecialBeanAbove();
        mSpecialBeanBelow = new SpecialBeanBelow();
        lists =new ArrayList<>();
        list = new ArrayList<>();
        id = getIntent().getStringExtra("id");
        //play();
        //头布局
        initHead();
        doSensorManager();
        loadData1();
//        play();
        loadData2();
        //适配器


    }

    private void initHead() {
        headView = LayoutInflater.from(this).inflate(R.layout.specia_details_head, null);
        mVolumeBrightnessLayout = headView.findViewById(R.id.operation_volume_brightness);
        mOperationBg = (ImageView) headView.findViewById(R.id.operation_bg);
        mOperationPercent = (ImageView) headView.findViewById(R.id.operation_percent);

        pb = (ProgressBar) headView.findViewById(R.id.loading_process_dialog_progressBar);
        mVideoView = (VideoView) headView.findViewById(R.id.speciaDetail_video_view);
        image_play = (ImageView) headView.findViewById(R.id.specia_details_play_iv); //播放
        image_fullScreen = (ImageView) headView.findViewById(R.id.speciaDetail_video_fullscreen); //全屏
        tvTitle = (TextView) headView.findViewById(R.id.speciaDetail_video_tag_title);
        tvTags = (TextView) headView.findViewById(R.id.speciaDetail_video_tag);
        tvPlaycounts = (TextView) headView.findViewById(R.id.speciaDetail_video_playcount);
        sb = new StringBuffer();
    }

    //注册重力感应器  屏幕旋转
    private void doSensorManager(){
        image_fullScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sm.unregisterListener(listener);
                Toast.makeText(getApplicationContext(), "点击切换屏幕", 0).show();
                if (stretch_flag) {
                    stretch_flag = false;
                    //切换成横屏
                    SpeciaDetailsActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

                } else {
                    stretch_flag = true;
                    //切换成竖屏
                    SpeciaDetailsActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            }
        });
        //注册重力感应器  屏幕旋转
        sm = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        sensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener = new OrientationSensorListener(handler);
        sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);

        //根据  旋转之后 点击 符合之后 激活sm
        sm1 = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        sensor1 = sm1.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener1 = new OrientationSensorListener2();
        sm1.registerListener(listener1, sensor1, SensorManager.SENSOR_DELAY_UI);
    }

    //加载上面网络数据

    private void loadData1() {
        RequestParams rp = new RequestParams(PATH_DETAIL+id+HEADUID);
        rp.setConnectTimeout(3000);
        x.http().get(rp, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mSpecialBeanAbove = new Gson().fromJson(result, SpecialBeanAbove.class);

                tvTitle.setText(mSpecialBeanAbove.getResult().getDetail().getTitle());
                tvPlaycounts.setText(mSpecialBeanAbove.getResult().getVideo().getPlayTimes() + "次播放");
                for (int i = 0; i < mSpecialBeanAbove.getResult().getTags().size(); i++) {
                    tagString = mSpecialBeanAbove.getResult().getTags().get(i);
                    sb.append(tagString + " ");
                }
                tvTags.setText(sb.toString());

                list.add(mSpecialBeanAbove);
                Log.e( "onSuccess:到底有几个1111？ ",lists.size()+"+==list="+list.size() );

                play(mSpecialBeanAbove.getResult().getVideo().getVideoUrl());
                mListView.addHeaderView(headView);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("onError: ", "错误");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("onSuccess: ", "完成");
            }

            @Override
            public void onFinished() {
                Log.e("onFinished: ", "结束");
            }
        });
    }
    private void loadData2() {
        RequestParams rp = new RequestParams(PATH_COMMENTS+id+BELOWUID);
        rp.setConnectTimeout(3000);
        x.http().get(rp, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                mSpecialBeanBelow = new Gson().fromJson(result, SpecialBeanBelow.class);

                list.add(mSpecialBeanBelow);
                Log.e( "onSuccess:到底有几个loadData2？ ","+==list="+list.size() );

                mAdapter = new SpecialDetailsAdapter(SpeciaDetailsActivity.this,list);

                mListView.setAdapter(mAdapter);
                Log.e( "onSuccess:到底有几个loadData2adapter之前？ ","+==list="+list.size() );

                mAdapter.notifyDataSetChanged();
                Log.e( "onSuccess:到底有几个22222notifyDataSetChange22？ ","+=====list="+list.size() );

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("onError: ", "错误1");
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Log.e("onSuccess: ", "完成1");
            }

            @Override
            public void onFinished() {
                Log.e("onFinished: ", "结束1");
            }
        });
    }


    //两个悬浮框点击事件
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.speciaDetail_video_back: //返回
                finish();
                break;
            case R.id.speciaDetail_video_share: //分享

                break;
        }
    }



    //视频播放
//    private void loadVideo(String path){
//        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        mMaxVolume = mAudioManager
//                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//        mVideoView.setVideoPath(path);
//        mMediaController = new MediaController(this);
//        mVideoView.setMediaController(mMediaController);
//        mVideoView.requestFocus();
//
//        mGestureDetector = new GestureDetector(this, new MyGestureListener());
//
//    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;

        // 处理手势结束
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                endGesture();
                break;
        }

        return super.onTouchEvent(event);
    }

    /** 手势结束 */
    private void endGesture() {
        mVolume = -1;
        mBrightness = -1f;

        // 隐藏
        mDismissHandler.removeMessages(0);
        mDismissHandler.sendEmptyMessageDelayed(0, 500);
    }

    private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        /** 双击 */
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (mLayout == VideoView.VIDEO_LAYOUT_ZOOM)
                mLayout = VideoView.VIDEO_LAYOUT_ORIGIN;
            else
                mLayout++;
            if (mVideoView != null)
//                mVideoView.setVideoLayout(mLayout, 0);
                SpeciaDetailsActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            return true;
        }

        /** 滑动 */
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            float mOldX = e1.getX(), mOldY = e1.getY();
            int y = (int) e2.getRawY();
            Display disp = getWindowManager().getDefaultDisplay();
            int windowWidth = disp.getWidth();
            int windowHeight = disp.getHeight();

            if (mOldX > windowWidth * 4.0 / 5)// 右边滑动
                onVolumeSlide((mOldY - y) / windowHeight);
            else if (mOldX < windowWidth / 5.0)// 左边滑动
                onBrightnessSlide((mOldY - y) / windowHeight);

            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }

    /** 定时隐藏 */
    private Handler mDismissHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mVolumeBrightnessLayout.setVisibility(View.GONE);
        }
    };

    /**
     * 滑动改变声音大小
     *
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        if (mVolume == -1) {
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mVolume < 0)
                mVolume = 0;

            // 显示
            mOperationBg.setImageResource(R.mipmap.ic_launcher);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }

        int index = (int) (percent * mMaxVolume) + mVolume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

        // 变更进度条
        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = findViewById(R.id.operation_full).getLayoutParams().width
                * index / mMaxVolume;
        mOperationPercent.setLayoutParams(lp);
    }

    /**
     * 滑动改变亮度
     *
     * @param percent
     */
    private void onBrightnessSlide(float percent) {
        if (mBrightness < 0) {
            mBrightness = getWindow().getAttributes().screenBrightness;
            if (mBrightness <= 0.00f)
                mBrightness = 0.50f;
            if (mBrightness < 0.01f)
                mBrightness = 0.01f;

            // 显示
            mOperationBg.setImageResource(R.mipmap.ic_launcher);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }
        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        lpa.screenBrightness = mBrightness + percent;
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
        else if (lpa.screenBrightness < 0.01f)
            lpa.screenBrightness = 0.01f;
        getWindow().setAttributes(lpa);

        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = (int) (findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness);
        mOperationPercent.setLayoutParams(lp);
    }


    @SuppressLint("NewApi")
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (mVideoView != null)
            mVideoView.setVideoLayout(mLayout, 0);
        super.onConfigurationChanged(newConfig);
        if (stretch_flag) {
            //切换成竖屏
            FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(screenHeight, DensityUtils.dip2px(this, 160));
            mVideoView.setLayoutParams(params1);
            Toast.makeText(getApplicationContext(), "竖屏", 0).show();

        }
        else {
            //切换成横屏
            FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(screenHeight,screenWidth);

            mVideoView.setLayoutParams(params1);

            Toast.makeText(getApplicationContext(), "横屏", 0).show();

        }

    }


    /**
     * 重力感应监听者
     */
    public class OrientationSensorListener implements SensorEventListener {
        private static final int _DATA_X = 0;
        private static final int _DATA_Y = 1;
        private static final int _DATA_Z = 2;

        public static final int ORIENTATION_UNKNOWN = -1;

        private Handler rotateHandler;

        public OrientationSensorListener(Handler handler) {
            rotateHandler = handler;
        }

        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        public void onSensorChanged(SensorEvent event) {

            if(sensor_flag!=stretch_flag)  //只有两个不相同才开始监听行为
            {
                float[] values = event.values;
                int orientation = ORIENTATION_UNKNOWN;
                float X = -values[_DATA_X];
                float Y = -values[_DATA_Y];
                float Z = -values[_DATA_Z];
                float magnitude = X*X + Y*Y;
                // Don't trust the angle if the magnitude is small compared to the y value
                if (magnitude * 4 >= Z*Z) {
                    //屏幕旋转时
                    float OneEightyOverPi = 57.29577957855f;
                    float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
                    orientation = 90 - (int)Math.round(angle);
                    // normalize to 0 - 359 range
                    while (orientation >= 360) {
                        orientation -= 360;
                    }
                    while (orientation < 0) {
                        orientation += 360;
                    }
                }
                if (rotateHandler!=null) {
                    rotateHandler.obtainMessage(888, orientation, 0).sendToTarget();
                }

            }
        }
    }

    public class OrientationSensorListener2 implements SensorEventListener {
        private static final int _DATA_X = 0;
        private static final int _DATA_Y = 1;
        private static final int _DATA_Z = 2;

        public static final int ORIENTATION_UNKNOWN = -1;

        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        public void onSensorChanged(SensorEvent event) {

            float[] values = event.values;

            int orientation = ORIENTATION_UNKNOWN;
            float X = -values[_DATA_X];
            float Y = -values[_DATA_Y];
            float Z = -values[_DATA_Z];

            /**
             * 这一段据说是 android源码里面拿出来的计算 屏幕旋转的 不懂 先留着 万一以后懂了呢
             */
            float magnitude = X*X + Y*Y;
            // Don't trust the angle if the magnitude is small compared to the y value
            if (magnitude * 4 >= Z*Z) {
                //屏幕旋转时
                float OneEightyOverPi = 57.29577957855f;
                float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
                orientation = 90 - (int)Math.round(angle);
                // normalize to 0 - 359 range
                while (orientation >= 360) {
                    orientation -= 360;
                }
                while (orientation < 0) {
                    orientation += 360;
                }
            }

            if (orientation>225&&orientation<315){  //横屏
                sensor_flag = false;
            }else if ((orientation>315&&orientation<360)||(orientation>0&&orientation<45)){  //竖屏
                sensor_flag = true;
            }

            if(stretch_flag== sensor_flag){  //点击变成横屏  屏幕 也转横屏 激活
                System.out.println("激活");
                sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);

            }
        }
    }



    //播放视频
    private void play(String path) {
        mVideoView.setVideoPath(path);   //设置视频网络地址
        // mVideoView.setVideoURI(Uri.parse(path)); //也可以是本地,也可以是网络地址
        final MediaController mediaController = new MediaController(this);
        mediaController.setVisibility(View.GONE);

        mVideoView.setMediaController(mediaController); //设置媒体控制器
        //  mVideoView.setVideoLayout(VideoView.VIDEO_LAYOUT_STRETCH, 0);   //设置视频的缩放参数,这里设置为拉伸
        mVideoView.requestFocus();
        //视频播放器的准备,此时播放器已经准备好了,此处可以设置一下播放速度,播放位置等等

        //mVideoView.start();
        mVideoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(final MediaPlayer mp, int what, int extra) {
                switch (what) {
                    //开始缓冲
                    case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                        pb.setVisibility(View.VISIBLE);
                        mp.pause();
                        break;
                    //缓冲结束
                    case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                        pb.setVisibility(View.GONE);
                        image_play.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                image_play.setVisibility(View.GONE);
                                mp.start();
                            }
                        });
                        break;
                    //正在缓冲
                    case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:
                        break;
                }
                return true;
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Toast.makeText(SpeciaDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                //此处设置播放速度为正常速度1
                mediaPlayer.setPlaybackSpeed(1.0f);
            }
        });
        //当播放完成后,从头开始
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                // mediaPlayer.seekTo(0);   //转到第一帧
                // mediaPlayer.start();     //开始播放
            }
        });
        mGestureDetector = new GestureDetector(this, new MyGestureListener());
    }



}
